# -*- coding: utf-8 -*-
# encoding=utf-8 vi:ts=4:sw=4:expandtab:ft=python
"""
Tool Interface
"""
import requests
import json
import time
import datetime
from flask import Flask
from flask_restful import Resource, Api
from flask import request
import argparse
import os


app = Flask(__name__)
api = Api(app)
API_PORT=8100


@app.route("/test-<int:toolid>")
def service(toolid):
    """
    Args:
        toolid: Tool ID.
    Returns:
        Http response(json).
    """
    framework_port_dict = {
            'paddle': 8100,
            }
    framework_name = 'paddle'
    port = str(framework_port_dict[framework_name] + toolid)
    request_url = request.url.replace(str(API_PORT), port)
    r = requests.get(request_url, \
        headers={'Content-Type':'application/json', 'Accept':'application/json', 'charset':'UTF-8'}, \
        data=json.dumps(request.get_json()))
    response_json = json.loads(r.text)

    callback = request.args['callback'] if 'callback' in request.args else ''
    token = request.args['token'] if 'token' in request.args else ''

    if callback:
        request_url = 'http://192.168.9.86:8080/api/tools/result/callback'
        callback_data = dict()
        callback_data['callback'] = True
        callback_data['access_token'] = token
        callback_data['status'] = "SUCCESS" if response_json['result'] == "PASS" else "FAIL"
        callback_data['result'] = json.dumps(response_json)
        r = requests.post(request_url,
                          headers={'Content-Type': 'application/x-www-form-urlencoded', 'Accept': '*/*',
                                   'charset': 'UTF-8'},
                          data=callback_data)
        return json.dumps(r.text, ensure_ascii=False)

    return response_json


@app.route("/version")
def get_version():
    """
    Args:
        toolid: Tool ID.
    Returns:
        Http response(json).
    """
    return {"status": 200, "version": "v0.1"}


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=API_PORT, debug=True)
